﻿using System;
using System.Text;
using System.Collections.Generic;
using NHibernate;
using Common;
using Educational.Model.Entity;
using Educational.Model.EntityManager;

namespace Educational.Business
{
    public class DepartmentAdmin
    {
        #region CreateDepartmentBySystem一键自动创建部门
        public static void CreateDepartmentBySystem(int schoolId)
        {
            ISession session = null;
            ITransaction trans = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                if (DepartmentManager.Gets1(session, schoolId).Count > 0)
                    throw new Exception("当前学校已经存在部门，如需一键自动生成，请先删除所有部门。");
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
            AddDepartment(schoolId, 0, "校委会");
            AddDepartment(schoolId, 0, "语文组");
            AddDepartment(schoolId, 0, "数学组");
            AddDepartment(schoolId, 0, "外语组");
            AddDepartment(schoolId, 0, "理化生组");
            AddDepartment(schoolId, 0, "政史地组");
            AddDepartment(schoolId, 0, "综合组");
            AddDepartment(schoolId, 0, "后勤组");
        }
        #endregion
        #region DeleteDepartment删除部门
        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="schoolId"></param>
        /// <param name="departmentId"></param>
        public static void DeleteDepartment(int schoolId, int departmentId)
        {
            ISession session = null;
            ITransaction trans = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                Basic.Model.Entity.Collision collision = new Basic.Model.Entity.Collision();
                collision.itemKey = "DeleteDepartment" + departmentId.ToString();
                Basic.Model.EntityManager.CollisionManager.AddItem(session, collision);

                Department department = DepartmentManager.Get2(session, schoolId, departmentId);
                if (department == null)
                    throw new Exception("当前学校不存在这个部门或者这个部门已经被删除");
                if (department.positions.Count > 0)
                    throw new Exception("当前部门存在下属职位，你必须先删除职位！");
                if (DepartmentManager.Gets2(session, schoolId, department.departmentId).Count > 0)
                    throw new Exception("当前部门存在下属部门，请先删除下属部门！");
                DepartmentManager.Delete(session, department);

                Basic.Model.EntityManager.CollisionManager.DeleteItem(session, collision);
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        #endregion
        #region UpdateDepartment修改部门
        /// <summary>
        /// 修改部门
        /// </summary>
        /// <param name="schoolId"></param>
        /// <param name="departmentId"></param>
        /// <param name="departmentParentId"></param>
        /// <param name="departmentName"></param>
        public static void UpdateDepartment(int schoolId,int departmentId, int departmentParentId, string departmentName)
        {
            ISession session = null;
            ITransaction trans = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                Basic.Model.Entity.Collision collision = new Basic.Model.Entity.Collision();
                collision.itemKey = "DeleteSchool" + schoolId.ToString();
                Basic.Model.EntityManager.CollisionManager.AddItem(session, collision);
                Basic.Model.Entity.Collision collision1 = new Basic.Model.Entity.Collision();
                collision1.itemKey = "DeleteDepartment" + departmentParentId.ToString();
                Basic.Model.EntityManager.CollisionManager.AddItem(session, collision1);
                Basic.Model.Entity.Collision collision2 = new Basic.Model.Entity.Collision();
                collision2.itemKey = "UpdateDepartment" + departmentParentId.ToString();
                Basic.Model.EntityManager.CollisionManager.AddItem(session, collision2);
                Basic.Model.Entity.Collision collision3 = new Basic.Model.Entity.Collision();
                collision3.itemKey = "DeleteDepartment" + departmentId.ToString();
                Basic.Model.EntityManager.CollisionManager.AddItem(session, collision3);
                Basic.Model.Entity.Collision collision4 = new Basic.Model.Entity.Collision();
                collision4.itemKey = "UpdateDepartment" + departmentId.ToString();
                Basic.Model.EntityManager.CollisionManager.AddItem(session, collision4);

                Department department = DepartmentManager.Get1(session, schoolId, departmentId);
                if (department == null)
                    throw new Exception("当前学校不存在这个部门或者这个部门已经被删除！");
                if (DepartmentManager.Get1(session, schoolId, departmentParentId) == null && departmentParentId != 0)
                    throw new Exception("所属部门不存在或者这个部门已经被删除！");
                IList<Department> departmentList = DepartmentManager.Gets1(session, schoolId);
                IList<int> departmentSelfAndChildIds = new List<int>();
                departmentSelfAndChildIds.Add(departmentId);
                GetChildDepartmentIds(departmentList, departmentSelfAndChildIds, departmentId);
                for (int i = 0; i < departmentSelfAndChildIds.Count; i++)
                {
                    if (departmentSelfAndChildIds[i] == departmentParentId)
                        throw new Exception("错误的参数！");
                }
                department.departmentName = departmentName;
                department.departmentParentId = departmentParentId;

                Basic.Model.EntityManager.CollisionManager.DeleteItem(session, collision);
                Basic.Model.EntityManager.CollisionManager.DeleteItem(session, collision1);
                Basic.Model.EntityManager.CollisionManager.DeleteItem(session, collision2);
                Basic.Model.EntityManager.CollisionManager.DeleteItem(session, collision3);
                Basic.Model.EntityManager.CollisionManager.DeleteItem(session, collision4);
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        public static void GetChildDepartmentIds(IList<Department> departmentList, IList<int> departmentSelfAndChildIds, int departmentParentId)
        {
            for (int i = 0; i < departmentList.Count; i++)
            {
                if (departmentList[i].departmentParentId == departmentParentId)
                {
                    departmentSelfAndChildIds.Add(departmentList[i].departmentId);
                    GetChildDepartmentIds(departmentList, departmentSelfAndChildIds, departmentList[i].departmentId);
                }
            }
        }
        #endregion
        #region AddDepartment添加部门
        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="schoolId"></param>
        /// <param name="departmentParentId"></param>
        /// <param name="departmentName"></param>
        public static void AddDepartment(int schoolId, int departmentParentId, string departmentName)
        {
            ISession session = null;
            ITransaction trans = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                Basic.Model.Entity.Collision collision = new Basic.Model.Entity.Collision();
                collision.itemKey = "DeleteSchool" + schoolId.ToString();
                Basic.Model.EntityManager.CollisionManager.AddItem(session, collision);
                Basic.Model.Entity.Collision collision1 = new Basic.Model.Entity.Collision();
                collision1.itemKey = "DeleteDepartment" + departmentParentId.ToString();
                Basic.Model.EntityManager.CollisionManager.AddItem(session, collision1);
                Basic.Model.Entity.Collision collision2 = new Basic.Model.Entity.Collision();
                collision2.itemKey = "UpdateDepartment" + departmentParentId.ToString();
                Basic.Model.EntityManager.CollisionManager.AddItem(session, collision2);

                Department department = new Department();
                department.school = SchoolManager.Get(session, schoolId);
                if (department.school == null)
                    throw new Exception("当前学校不存在或者已经被删除！");
                if (DepartmentManager.Get1(session, schoolId, departmentParentId) == null && departmentParentId != 0)
                    throw new Exception("所属部门不存在或者这个部门已经被删除！");
                department.departmentName = departmentName;
                department.departmentParentId = departmentParentId;
                DepartmentManager.Add(session, department);

                Basic.Model.EntityManager.CollisionManager.DeleteItem(session, collision);
                Basic.Model.EntityManager.CollisionManager.DeleteItem(session, collision1);
                Basic.Model.EntityManager.CollisionManager.DeleteItem(session, collision2);
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        #endregion
        #region GetsDepartment获取部门列表，并根据层级关系进行排序
        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <param name="schoolId"></param>
        /// <returns></returns>
        public static IList<Educational.VO.Department> GetsDepartment(int schoolId)
        { 
            ISession session = null;
            ITransaction trans = null;
            IList<Department> entityData = null;
            IList<Educational.VO.Department> departmentList = new List<Educational.VO.Department>();
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                entityData = DepartmentManager.Gets1(session, schoolId);
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
            foreach (Department department in entityData)
            {
                Educational.VO.Department VODepartment = new Educational.VO.Department();
                VODepartment.departmentId = department.departmentId;
                VODepartment.departmentName = department.departmentName;
                VODepartment.departmentParentId = department.departmentParentId;
                departmentList.Add(VODepartment);
            }
            return departmentList;
        }

        #endregion
        #region GetDepartmentSelectHtmlString获取所有部门的下拉列表HTML代码
        /// <summary>
        /// 获取所有部门的下拉列表HTML代码
        /// </summary>
        /// <param name="school"></param>
        /// <param name="selectId"></param>
        /// <param name="selectName"></param>
        /// <param name="selectedId"></param>
        /// <returns></returns>
        public static string GetDepartmentSelectHtmlString(Educational.VO.School school, string selectId, string selectName, int selectedId)
        {
            ISession session = null;
            ITransaction trans = null;
            StringBuilder html = new StringBuilder();
            IList<Department> entityData = null;
            IList<Educational.VO.Department> departmentList = new List<Educational.VO.Department>();
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                entityData = DepartmentManager.Gets1(session, school.schoolId);
                trans.Commit();
                Educational.VO.Department department = new Educational.VO.Department();
                department.departmentId = 0;
                department.departmentName = school.schoolName;
                department.departmentParentId = -1;
                departmentList.Add(department);
                ToSelectList(departmentList, entityData, 0, 1);
                html.AppendFormat("<select id=\"{0}\" name=\"{1}\" class=\"input\">", selectId, selectName);
                for (int i = 0; i < departmentList.Count; i++)
                {
                    if (departmentList[i].departmentId != selectedId)
                        html.AppendFormat("<option value=\"{0}\">{1}</option>", departmentList[i].departmentId, departmentList[i].departmentName);
                    else
                        html.AppendFormat("<option value=\"{0}\" selected=\"selected\">{1}</option>", departmentList[i].departmentId, departmentList[i].departmentName);
                }
                html.Append("</select>");
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                html.Append("读取部门下拉列表失败");
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
            return html.ToString();
        }


        /// <summary>
        /// 对一个部门列表按照层级关系进行排序
        /// </summary>
        /// <param name="departmentList"></param>
        /// <param name="entityData"></param>
        /// <param name="departmentParentId"></param>
        /// <param name="level"></param>
        private static void ToSelectList(IList<Educational.VO.Department> departmentList, IList<Department> entityData, int departmentParentId, int level)
        {
            foreach (Department department in entityData)
            {
                if (department.departmentParentId == departmentParentId)
                {
                    Educational.VO.Department VODepartment = new Educational.VO.Department();
                    VODepartment.departmentId = department.departmentId;
                    VODepartment.departmentName = department.departmentName;
                    for (int i = 0; i < level; i++)
                        VODepartment.departmentName = "－" + VODepartment.departmentName;
                    VODepartment.departmentParentId = department.departmentParentId;
                    departmentList.Add(VODepartment);
                    ToSelectList(departmentList, entityData, department.departmentId, level + 1);
                }
            }
        }
        #endregion
    }
}
